package com.lccviolet;

import java.lang.ref.SoftReference;

/**
 * @author LiChaochao
 * @Date 2021/9/22 20:39
 * @Description 软引用：内存够用不回收，不够用才回收
 */
public class SoftReferenceDemo {

    public static void memoryEnough() {
        Object o1 = new Object();
        SoftReference<Object> o2 = new SoftReference<>(o1);

        System.out.println("o1 = " + o1);
        System.out.println("o2 = " + o2.get());

        o1 = null;
        System.gc();

        System.out.println("o1 = " + o1);
        System.out.println("o2 = " + o2.get());

    }

    public static void memoryNotEnough() {
        Object o1 = new Object();
        SoftReference<Object> o2 = new SoftReference<>(o1);

        System.out.println("o1 = " + o1);
        System.out.println("o2 = " + o2.get());

        o1 = null;

        try {
            /*
            * 手动产生大对象，且配置小内存，让内存不够导致OOM，查看软引用情况
            * */
            byte[] bytes = new byte[30 * 1024 * 1024];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("o1 = " + o1);
            System.out.println("o2 = " + o2.get());
        }
    }

    public static void main(String[] args) {
        memoryEnough();

        System.out.println();
        System.out.println("========================================================");
        System.out.println();

        memoryNotEnough();
    }
}
